﻿module Sustainalytics.GovernanceReports {

    import Common = Sustainalytics.Common;
    import Company = Sustainalytics.Company;

    export class GovernanceService implements IGovernanceService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private $location: ng.ILocationService;
        private staticObjects: IStaticObjects;
        private notificationFactory: INotificationFactory;
        private $upload: any;

        // Ctor.
        constructor($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, $upload: any) {
            this.$q = $q;
            this.$http = $http;
            this.$location = $location;
            this.staticObjects = staticObjects;
            this.notificationFactory = notificationFactory;
            this.$upload = $upload;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getMessageByInternalCode(err['code']));
        }

        // get filtered list of events 
        public getCompanyProfileAndAlerts(companyId: string): ng.IPromise<GovernanceProfileDto> {
            var ctx = this;
            var def = this.$q.defer();

            var url = '/governanceserv/api/v1/governanceadmin/' + companyId;

            var promise = this.$http.get(url);
            promise.success(function (data)
            {
                def.resolve(data);
            })
            .error(function (err)
            {
                ctx.showError(err);
                def.reject();
            })
            return promise;
        }

        public getCompanyById(id: string): ng.IHttpPromise<Company.CorporateDataExtendedDto> {

            var url: string = '/governanceserv/api/v1/company/' + id;

            var promise: ng.IHttpPromise<Company.CorporateDataExtendedDto> = this.$http.get(url);

            return promise;
        }

        private filesUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/governanceserv/api/v1/files/";
        }

        public fileUpload(file: File, id: string): ng.IPromise<{}> {
            var ctx = this;
            var def = ctx.$q.defer();
            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: /*(id) ? "PUT" :*/ "POST",
                    url: ctx.filesUrl() /*+ ((id) ? id : "")*/,
                    headers: { 'Content-Disposition': 'attachment; filename=\"' + file.name +'\"', 'Content-Type': file.type, },
                    data: reader.result
                })
                    .progress(evt => { console.log('percent: ' + (100.0 * evt.loaded / evt.total)); })
                    .success((data, status, headers, config) => { def.resolve(data) });
            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }

        public saveProfile(dto: GovernanceProfileDto): ng.IHttpPromise<GovernanceProfileDto> {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadmin/';
            return ctx.$http.post<GovernanceProfileDto>(url, dto);
        }

        public deleteProfile(companyId: string) {
            var ctx = this;
            var url = '/governanceserv/api/v1/governanceadmin/' + companyId;
            return ctx.$http.delete<GovernanceProfileDto>(url);
        }
    }

    // register service with News Angular module
    angular.module('Sustainalytics.GovernanceReports').factory('GovernanceService', function ($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, $upload: any) {
        var srv = new GovernanceService($q, $http, $location, notificationFactory, staticObjects, $upload);
        return srv;
    });
}  